import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json, time, sys, os, logging
os.sys.path.append('../utils/constants/')
from constants import *
os.sys.path.append('../utils/memcacheDao/')
import memcacheDao
os.sys.path.append('../modules/user/')
import userLogic

from tornado.options import define, options
reload(sys)  
sys.setdefaultencoding("utf-8")  


class UserHandler(tornado.web.RequestHandler):
    #def get(self):
    #    self.write("hello, xxoo123")

    def post(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        argument_dict = {}
        ret = {}
        if strType == 'checkin':
            #argument_dict = self.get_checkin_argument()
            user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
            string_base64 = self.get_argument('code', '')
            #print string_base64
            ret = user_logic.checkin(string_base64)
            logmsg = 't:%s r:%u' % (strType, ret['retcode'],)
            if 0 == ret['retcode']:
                bonus_ret = user_logic.bonus4checkin(ret['retbody']['user_id'])
                logmsg += ' bonus:%u' % (bonus_ret['retcode'],)
            else:
                logmsg += ' code:%s' % (string_base64,)
            logging.info(logmsg)
        elif strType == 'checkuname':
            #argument_dict = self.get_register_argument()
            user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
            uname = self.get_argument('uname')
            #print string_base64
            ret = user_logic.check_uname(uname)
            logging.info('t:%s r:%u un:%s' % (strType, ret['retcode'], uname,))
        elif strType == 'register':
            #argument_dict = self.get_register_argument()
            user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
            string_base64 = self.get_argument('code')
            #print string_base64
            ret = user_logic.register(self.request.remote_ip, string_base64)
            if 0 == ret['retcode']:
                logging.info('t:%s r:%u' % (strType, ret['retcode'],))
            else:
                logging.warning('t:%s r:%u code:%s' % (strType, ret['retcode'], string_base64,))
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        #print ret
        self.write(json.dumps(ret))
